#!/usr/bin/python3
import cgi, os
import cgitb
# Apache2 vhost 设置中已经设置了 SetENV PYTHONIOENCODING=UTF-8
# 所以无需在设置 sys.stdout 的编码方式为 utf8，否则要去掉下面两行的配置
#import sys,codecs
#sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
cgitb.enable()  
form = cgi.FieldStorage()
title = '#Success#'
# path : 上传文件存储目录  
path = '/home/backup/MyShare/upload/'
try:
    fileitem = form['uploadfile'] 
    fn = os.path.basename(fileitem.filename)
    # Internet Explorer will attempt to provide full path for filename fix  
    fn = fn.split('\\')[-1]
    filepath = path + fn  
  
    # Open the file for writing   
    f = open(filepath.encode('utf-8') , 'wb')  
  
    # Read the file in chunks  
    for chunk in fileitem.file:
        f.write(chunk)  
    f.close()  

    message = fn  
except Exception as e:  
    message = e
    title = '#Fail#'
    
print('Content-type:text/html;charset="utf-8"\n\n')
print( """<html>
<head><title>%s</title></head>
<body>%s</body>
</html>""" % (title,message) )
